package com.example.game2048;

import java.util.ArrayList;
import java.util.List;

import com.example.util.NumList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;

public class MyGridView extends GridLayout {

	private MyCard[][] cards = new MyCard[4][4];
	private List<Point> emptyPoints = new ArrayList<Point>();
	
	

	public MyGridView(Context context) {
		super(context);
		initGame();
	}

	public MyGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initGame();
	}

	public MyGridView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initGame();
	}
	
	public MyCard[][] getMyCards() {
		return cards;
	}
	
	public void setMyCards(int[] nums) {
		for(int x=0;x<4;x++) {
			for(int y=0;y<4;y++) {
				cards[x][y].setNum(nums[x*4 + y]);
			}
		}
	}

	private void initGame() {
		setColumnCount(4);
		setRowCount(4);

		// 设置背景颜色
		setBackgroundColor(0xFFBCAEA1);

		setOnTouchListener(new OnTouchListener() {

			private float startx, starty, offerx, offery;

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				switch(arg1.getAction()) {
				case MotionEvent.ACTION_DOWN:
					startx = arg1.getX();
					starty = arg1.getY();
					break;
				case MotionEvent.ACTION_UP:
					offerx = arg1.getX() - startx;
					offery = arg1.getY() - starty;
					if(Math.abs(offerx) > Math.abs(offery)) {
						// 横向偏移量大
						if(offerx > 5) {
							moveright();
						} else if(offerx < -5) {
							moveleft();
						}
					} else {
						// 纵向偏移量大
						if(offery > 5) {
							movedown();
						} else if(offery < -5) {
							moveup();
						}
					}
					break;
				}
				return true;
			}
		});
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);

		int cardwidth = (Math.min(w, h) - 10) / 4;

		addCards(cardwidth, cardwidth);

		startGame();
	}

	private void initCards() {
		// 将所有的Card的num置为0
		for(int x = 0; x < 4; x++) {
			for(int y = 0; y < 4; y++) {
				cards[x][y].setNum(0);
			}
		}

	}
	
	

	public void startGame() {
		MainActivity.getMainActivity().clearRecords();
		MainActivity.getMainActivity().setUndoTimes(3);
		
		initCards();
		// 添加一个随机Card
		addRandomCard();
		
		
		// 添加一个随机Card
		addRandomCard();

		updateScore(0);
	}

	// 将所有的Card创建，并加入到MyGridView中
	private void addCards(int cardWidth, int cardHeight) {

		MyCard c;

		for(int x = 0; x < 4; x++) {
			for(int y = 0; y < 4; y++) {
				c = new MyCard(getContext());
				addView(c, cardWidth, cardHeight);
				cards[x][y] = c;
			}
		}
	}

	private void addRandomCard() {
		emptyPoints.clear();

		// 设置所有的Card的文本属性,并添加一个新的非空Card

		for(int x = 0; x < 4; x++) {
			for(int y = 0; y < 4; y++) {
				if(cards[x][y].getNum() <= 0) {
					emptyPoints.add(new Point(x, y));
				}

			}
		}
		
		
		Point p = emptyPoints
				.remove((int) (Math.random() * emptyPoints.size()));
		cards[p.x][p.y].setNum(Math.random() > 0.1 ? 2 : 4);

	}
	
	public NumList getNumList() {
		NumList currentNumList = new NumList(17);
		int i = 0;
		for(MyCard[] myCards : getMyCards()) {
			for(MyCard myCard : myCards) {
				currentNumList.setNumOfIndex(i++, myCard.getNum());
			}
		}
		currentNumList.setNumOfIndex(16, MainActivity.getMainActivity().getScore());
		return currentNumList;
	}

	private void moveup() {
		if(checkComplete()) {
			showAgainDialog();
		}
		//MainActivity.getMainActivity().saveGame();
		boolean flag = false;
		int increment = 0;
		NumList currentNumList = getNumList();
		for(int y = 0; y < 4; y++) {
			int x = 0;
			int x1 = x + 1;

			while(x1 < 4) {
				if(cards[x1][y].getNum() > 0) {
					if(cards[x][y].getNum() <= 0) {
						cards[x][y].setNum(cards[x1][y].getNum());
						cards[x1][y].setNum(0);
						flag = true;
					} else {
						if(cards[x][y].equals(cards[x1][y])) {
							cards[x][y].setNum(cards[x][y].getNum() * 2);
							cards[x1][y].setNum(0);
							increment += cards[x][y].getNum();
							Log.d("increment", increment+"");
							flag = true;
						} else if(x1 - x > 1) {
							cards[x+1][y].setNum(cards[x1][y].getNum());
							cards[x1][y].setNum(0);
							flag = true;
						}
						x++;
					}
				} 
				x1++;
			}			
		}
		
		if(flag) {
			MainActivity.getMainActivity().saveGame(currentNumList);
			updateScore(increment);
			addRandomCard();
			
		}
	}

	private void movedown() {
		if(checkComplete()) {
			showAgainDialog();
		}
		//MainActivity.getMainActivity().saveGame();
		boolean flag = false;
		int increment = 0;
		NumList currentNumList = getNumList();
		for(int y = 0; y < 4; y++) {
			int x = 3;
			int x1 = x - 1;

			while(x1 >= 0) {
				if(cards[x1][y].getNum() > 0) {
					if(cards[x][y].getNum() <= 0) {
						cards[x][y].setNum(cards[x1][y].getNum());
						cards[x1][y].setNum(0);
						flag = true;
					} else {
						if(cards[x][y].equals(cards[x1][y])) {
							cards[x][y].setNum(cards[x][y].getNum() * 2);
							cards[x1][y].setNum(0);
							increment += cards[x][y].getNum();
							Log.d("increment", increment+"");
							flag = true;
						} else if(x - x1 > 1) {
							cards[x-1][y].setNum(cards[x1][y].getNum());
							cards[x1][y].setNum(0);
							flag = true;
						}
						x--;
					}
				} 
				x1--;
			}			
		}
		
		if(flag) {
			MainActivity.getMainActivity().saveGame(currentNumList);
			updateScore(increment);
			addRandomCard();
			
		}
	}

	private void moveleft() {
		if(checkComplete()) {
			showAgainDialog();
		}
		//MainActivity.getMainActivity().saveGame();
		boolean flag = false;
		int increment = 0;
		NumList currentNumList = getNumList();
		for(int x = 0; x < 4; x++) {
			int y = 0;
			int y1 = y + 1;

			while(y1 < 4) {
				if(cards[x][y1].getNum() > 0) {
					if(cards[x][y].getNum() <= 0) {
						cards[x][y].setNum(cards[x][y1].getNum());
						cards[x][y1].setNum(0);
						flag = true;
					} else {
						if(cards[x][y].equals(cards[x][y1])) {
							cards[x][y].setNum(cards[x][y].getNum() * 2);
							cards[x][y1].setNum(0);
							increment += cards[x][y].getNum();
							Log.d("increment", increment+"");
							flag = true;
						} else if(y1 - y > 1) {
							cards[x][y+1].setNum(cards[x][y1].getNum());
							cards[x][y1].setNum(0);
							flag = true;
						}
						y++;
					}
				} 
				y1++;
			}			
		}
		if(flag) {
			MainActivity.getMainActivity().saveGame(currentNumList);
			updateScore(increment);
			addRandomCard();
			
		}
	}

	private void moveright() {
		if(checkComplete()) {
			showAgainDialog();
		}
//		MainActivity.getMainActivity().saveGame();
		boolean flag = false;
		int increment = 0;
		NumList currentNumList = getNumList();
		for(int x = 0; x < 4; x++) {
			int y = 3;
			int y1 = y - 1;

			while(y1 >= 0) {
				if(cards[x][y1].getNum() > 0) {
					if(cards[x][y].getNum() <= 0) {
						cards[x][y].setNum(cards[x][y1].getNum());
						cards[x][y1].setNum(0);
						flag = true;
					} else {
						if(cards[x][y].equals(cards[x][y1])) {
							cards[x][y].setNum(cards[x][y].getNum() * 2);
							cards[x][y1].setNum(0);
							increment += cards[x][y].getNum();
							Log.d("increment", increment+"");
							flag = true;
						} else if(y - y1 > 1) {
							cards[x][y-1].setNum(cards[x][y1].getNum());
							cards[x][y1].setNum(0);
							flag = true;
						}
						y--;
					}
				} 
				y1--;
			}			
		}
		if(flag) {
			MainActivity.getMainActivity().saveGame(currentNumList);
			updateScore(increment);
			addRandomCard();
			
		}
	}

	private void showAgainDialog() {
		new AlertDialog.Builder(getContext())
				.setTitle("You Lose!")
				.setMessage("Try Again.")
				.setPositiveButton("Again",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								startGame();
								MainActivity.getMainActivity().clearScore();
							}
						}).show();

	}

	private boolean checkComplete() {	
		for(int x = 0; x < 4; x++) {
			for(int y = 0; y < 4; y++) {
				if(cards[x][y].getNum() == 0
						|| (x > 0 && cards[x - 1][y].equals(cards[x][y]))
						|| (x < 3 && cards[x + 1][y].equals(cards[x][y]))
						|| (y > 0 && cards[x][y - 1].equals(cards[x][y]))
						|| (y < 3 && cards[x][y + 1].equals(cards[x][y]))) {
					return false;
				}
			}
		}
		
		return true;
	}

	public void updateScore(int increment) {
		int largest = 0;
		for(int x = 0; x < 4; x++) {
			for(int y = 0; y < 4; y++) {
				if(largest < cards[x][y].getNum()) {
					largest = cards[x][y].getNum();
				}
			}
		}
		MainActivity.getMainActivity().refreshScore(largest, increment);
	}

}
